package com.zbw.wesley_ui.treeListView;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import java.util.List;

/**
 * tree适配器
 */
public abstract class TreeListViewAdapter extends BaseAdapter {

	protected Context mContext;
	/**
	 * 存储所有可见的Node
	 */
	protected List<Node> mNodes;
	protected LayoutInflater mInflater;
	/**
	 * 存储所有的Node
	 */
	protected List<Node> mAllNodes;

	/**
	 * 点击的回调接口
	 */
	public OnTreeNodeClickListener onTreeNodeClickListener;

	public interface OnTreeNodeClickListener {
		/**
		 * 处理node click事件
		 * @param node
		 * @param position
		 */
		void onClick(Node node, int position);
		/**
		 * 处理checkbox选择改变事件
		 * @param node
		 * @param position
		 * @param checkedNodes
		 */
		void onCheckChange(Node node, int position, List<Node> checkedNodes);
	}

	public void setOnTreeNodeClickListener(
			OnTreeNodeClickListener onTreeNodeClickListener) {
		this.onTreeNodeClickListener = onTreeNodeClickListener;
	}

	/**
	 * 
	 * @param mTree view
	 * @param context 上下文对象
	 * @param data 数据
	 * @param defaultExpandLevel 默认展开几级树
	 * @param isHide 选择框是否隐藏
	 *
	 */
	public TreeListViewAdapter(ListView mTree, Context context, List<Node> data,
                               int defaultExpandLevel, boolean isHide)
			throws IllegalArgumentException, IllegalAccessException {

		mContext = context;
		/**
		 * 对所有的Node进行排序
		 */
		mAllNodes = TreeHelper
				.getSortedNodes(data, defaultExpandLevel, isHide);
		/**
		 * 过滤出可见的Node
		 */
		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
		mInflater = LayoutInflater.from(context);

		/**
		 * 设置节点点击时，可以展开以及关闭；并且将ItemClick事件继续往外公布
		 */
		mTree.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				expandOrCollapse(position);
				checkItemTextColor(position);
				if (onTreeNodeClickListener != null) {
					onTreeNodeClickListener.onClick(mNodes.get(position),position);
				}
			}
		});
	}

	/**
	 * 用于适配器显示选中的item
	 * @param position 下标
	 */
	private void checkItemTextColor(int position){
		for(Node n:mNodes){
			n.setCheckedItem(false);
		}
		Node n = mNodes.get(position);
		if(n!=null){
			n.setCheckedItem(true);
		}
		notifyDataSetChanged();
	}

	/**
	 * 相应ListView的点击事件 展开或关闭某节点
	 * 
	 * @param position
	 */
	public void expandOrCollapse(int position) {
		Node n = mNodes.get(position);
		if (n != null)// 排除传入参数错误异常
		{
			if (!n.isLeaf()) {
				n.setExpand(!n.isExpand());
				mNodes = TreeHelper.filterVisibleNode(mAllNodes);
				notifyDataSetChanged();// 刷新视图
			}
		}
	}

	@Override
	public int getCount() {
		return mNodes.size();
	}

	@Override
	public Object getItem(int position) {
		return mNodes.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final Node node = mNodes.get(position);
		convertView = getConvertView(node, position, convertView, parent);
		// 设置内边距
		convertView.setPadding(node.getLevel() * 30, 3, 3, 3);
		return convertView;
	}

	public abstract View getConvertView(Node node, int position,
                                        View convertView, ViewGroup parent);

	/**
	 * 更新
	 * @param isHide
	 */
	public void updateView(boolean isHide){
		for(Node node:mAllNodes){
			node.setHideChecked(isHide);
		}
		this.notifyDataSetChanged();
	}

	public List<Node> getAllNodes() {
		return mAllNodes;
	}

	public void setAllNodes(List<Node> allNodes) {
		mAllNodes = allNodes;
	}

	/**
	 * 删除
	 * @param node 对象
	 */
	public void delNode(Node node){
		//1.先判断是否有子节点
		if(!node.isLeaf()){
			//有子节点，先删除子节点集合
			mAllNodes.removeAll(node.getChildrenNodes());
		}
		//2.在删除本对象
		mAllNodes.remove(node);
		//3.再删除父节点子集合中的自己
        //3.1先判断是否有父节点
        if(!"0".equals(node.getpId())){
            //不是一级目录，说明有父节点
            for (Node n:mAllNodes) {
                //遍历找父节点对象
                if(n.getId().equals(node.getpId())){
                    //把父节点子集合中的自己删掉
                    n.getChildrenNodes().remove(node);
                    break;
                }
            }
        }
		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
		notifyDataSetChanged();
	}

	/**
	 * 增加
	 * @param node 对象
	 */
	public void addNode(Node node){
		for (Node n:mAllNodes) {
			if(n.getId().equals(node.getId())){
				throw new RuntimeException("新增节点ID已存在！");
			}
		}

		if("0".equals(node.getpId())){
			mAllNodes.add(node);
		}else {
			for (int j = 0; j < mAllNodes.size(); j++) {
				Node m = mAllNodes.get(j);
				if (node.getpId().equals(m.getId())) {
					node.setParent(m);
					TreeIndex treeIndex = new TreeIndex();
					getPosition(m,treeIndex);
					m.getChildrenNodes().add(node);
					mAllNodes.add(j+treeIndex.getIndex() + 1, node);
					break;
				}
			}
		}

		mNodes = TreeHelper.filterVisibleNode(mAllNodes);
		notifyDataSetChanged();
	}

	/**
	 * 计算新增item 位置    位置 = 父对象位置+父对象的子集合总数之和+1
	 * @param node 父对象
	 * @param index 计数器
	 */
	private void getPosition(Node node,TreeIndex index){
//		Log.i("index长度",index+"");
//		Log.i("node长度",node.getChildrenNodes().size()+"");
		index.setIndex(index.getIndex()+node.getChildrenNodes().size());
		for (int i = 0; i <node.getChildrenNodes().size() ; i++) {
			getPosition(node.getChildrenNodes().get(i),index);
		}
	}

}
